import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

// 公共路由 - 所有用户都可访问
const publicRoutes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue')
  }
]

// 管理员路由
export const adminRoutes: Array<RouteRecordRaw> = [
  {
    path: '/admin',
    name: 'AdminHome',
    component: () => import('../views/admin/AdminHome.vue'),
    meta: { requiresAuth: true, role: 'admin' }
  },
  {
    path: '/admin/users',
    name: 'UserManagement',
    component: () => import('../views/admin/UserManagement.vue'),
    meta: { requiresAuth: true, role: 'admin' }
  }
]

// 普通用户路由
export const userRoutes: Array<RouteRecordRaw> = [
  {
    path: '/user',
    name: 'UserHome',
    component: () => import('../views/user/UserHome.vue'),
    meta: { requiresAuth: true, role: 'user' }
  },
  {
    path: '/user/profile',
    name: 'UserProfile',
    component: () => import('../views/user/UserProfile.vue'),
    meta: { requiresAuth: true, role: 'user' }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes: publicRoutes
})

// 根据用户角色动态添加路由
export function addRoutesByRole(role: string) {
  // 清除原有的动态路由（通配符路由除外）
  router.getRoutes().forEach(route => {
    if (route.name && route.name !== 'Login' && route.name !== 'NotFound') {
      router.removeRoute(route.name)
    }
  })
  
  // 添加新的动态路由
  const routes = role === 'admin' ? adminRoutes : userRoutes
  routes.forEach(route => {
    router.addRoute(route)
  })
  
  // 添加通配符路由（确保它是最后加入的）
  router.addRoute({
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  })
}

// 记录是否已添加路由，避免重复添加
let hasAddedRoutes = false

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  const isLoggedIn = sessionStorage.getItem('isLoggedIn') === 'true'
  const userRole = sessionStorage.getItem('userRole')
  
  // 如果用户已登录但路由尚未添加
  if (isLoggedIn && userRole && !hasAddedRoutes) {
    // 添加路由
    addRoutesByRole(userRole)
    hasAddedRoutes = true
    
    // 如果目标路由不是根路径，则重定向（确保路由表已更新）
    if (to.path !== '/') {
      next({ path: to.fullPath, replace: true })
      return
    }
  }

  // 检查是否需要认证
  if (to.meta.requiresAuth && !isLoggedIn) {
    next({ name: 'Login' })
  } 
  // 检查角色权限
  else if (to.meta.role && to.meta.role !== userRole) {
    next({ name: 'NotFound' })
  } else {
    next()
  }
})

export default router 